﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;


namespace Deployment.Data.Variable
{
    [XmlRoot("ProjectVariables")]
    [Serializable()]
    public class VariablesFile : NotifyPropertyChanged
    {
        private ObservableSortedList<AbstractVariable> _variables;

        public VariablesFile()
        {
            _variables = new ObservableSortedList<AbstractVariable>(4, new VariableComparer());
        }

        public void AddVariable(AbstractVariable newVariable)
        {
            _variables.Add(newVariable);
        }

        public bool RemoveVariable(AbstractVariable variable)
        {
            return _variables.Remove(variable);
        }

        [XmlArray("Variables")]
        [XmlArrayItem("Variable", Type=typeof(VariableXmlSerializer<AbstractVariable>))]
        public ObservableSortedList<AbstractVariable> Variables
        {
            get { return _variables; }
        }

        private class VariableComparer : IComparer<AbstractVariable>
        {

            public int Compare(AbstractVariable x, AbstractVariable y)
            {
                if (x == null && y == null)
                    return 0;
                if (x == null && y != null)
                    return -1;
                if (x != null && y == null)
                    return 1;

                int eCompare = string.Compare(x.EnvironmentName, 
                    y.EnvironmentName, true);

                if (eCompare == 0)
                    return string.Compare(x.Name, y.Name, true);

                return eCompare;
            }
        }

        public void SaveToFile(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
                throw new ArgumentException("filePath cannot be null or empty.");

            using (StreamWriter sw = new StreamWriter(filePath, false))
            {
                XmlSerializer xml = new XmlSerializer(typeof(VariablesFile));
                xml.Serialize(sw, this);
                sw.Close();
            }
        }

        public static VariablesFile LoadFromFile(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                throw new ArgumentException("fileName cannot be null or empty.");
            if (!File.Exists(fileName))
                throw new FileNotFoundException("Unable to locate input file", fileName);

            VariablesFile obj;
            using (FileStream inStream = new FileStream(fileName, FileMode.Open))
            {
                XmlSerializer xml = new XmlSerializer(typeof(VariablesFile));

                obj = (VariablesFile)xml.Deserialize(inStream);
            }
            return obj;
        }
    }
}
